package com.xia.springboot.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.xia.springboot.common.Result;
import com.xia.springboot.controller.dto.CartItem;
import com.xia.springboot.entity.Item;
import com.xia.springboot.entity.Order;
import com.xia.springboot.entity.User;
import com.xia.springboot.entity.UserCart;
import com.xia.springboot.mapper.ItemMapper;
import com.xia.springboot.mapper.UserCartMapper;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

@RestController
@RequestMapping("/cart")
public class UserCartController {

    @Resource
    UserCartMapper userCartMapper;


    @Resource
    ItemMapper itemMapper;

    @PostMapping
    public Result<?> save(@RequestBody UserCart userCartReq, @SessionAttribute("user") User user){

        UserCart insert = new UserCart();
        insert.setItemId(userCartReq.getItemId());
        insert.setQuantity(userCartReq.getQuantity());
        insert.setUserId(user.getId());

        Integer userId = user.getId();
        Integer itemId = userCartReq.getItemId();

        LambdaQueryWrapper<UserCart> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UserCart::getUserId, userId)
            .eq(UserCart::getItemId, itemId);

        UserCart exists = userCartMapper.selectOne(queryWrapper);
        if(exists == null){
            userCartMapper.insert(insert);
        }else{
            int newQuantity = exists.getQuantity() + userCartReq.getQuantity();
            UserCart update = new UserCart();
            update.setId(exists.getId());
            update.setQuantity(newQuantity);
            userCartMapper.updateById(update);
        }
        return Result.success(null);
    }



    //根据订单ID删除订单
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id){
        userCartMapper.deleteById(id);
        return Result.success();
    }


    /**
     * 查询对应用户的订单信息
     * @param pageNum 当前页码
     * @param pageSize 每一页的条数
     * @param search 搜索的商品名
     * @return 返回分页好的数据表
     */
    @GetMapping("")
    public Result<?> findUserOrder(@RequestParam(defaultValue = "1") Integer pageNum,
        @RequestParam(defaultValue = "10") Integer pageSize,
        @RequestParam(defaultValue = "") String search, @SessionAttribute("user") User user
    ) {
        Integer userId= user.getId();
        //新建分页对象
        IPage<UserCart> page = new Page<>(pageNum, pageSize);
        //新建模糊查询对象,这里有个注意事项，你模糊项查询的对应项不能为null，为null就查不出来
        //LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>lambdaQuery().like(User::getUsername, search);
        LambdaQueryWrapper<UserCart> queryWrapper = Wrappers.lambdaQuery();
        // 给查询对象加上ID限制和日期降序
        queryWrapper.eq(UserCart::getUserId,userId).orderByDesc(UserCart::getCreateTime);
        IPage<UserCart> userPage = userCartMapper.selectPage(page, queryWrapper);
        List<UserCart> cartList = userPage.getRecords();

        Set<Integer> itemIdSet = cartList.stream().map(cart -> cart.getItemId()).collect(Collectors.toSet());

        List<Item> itemList = itemIdSet.size() == 0 ? Lists.newLinkedList() : itemMapper.selectBatchIds(itemIdSet);
        Map<Integer,Item> idItemMap = itemList.stream().collect(Collectors.toMap(item -> item.getId(), item -> item));

        List<CartItem> cartItemList = Lists.newLinkedList();

        for(UserCart userCart : cartList){
            CartItem cartItem = new CartItem(userCart.getId(), idItemMap.get(userCart.getItemId()), userCart.getQuantity());
            cartItemList.add(cartItem);
        }

        Page<CartItem> result = new Page<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
        result.setRecords(cartItemList);

        return Result.success(result);
    }

    @GetMapping("/count")
    public Result<?> userCartItemCount(@SessionAttribute("user") User user) {
        LambdaQueryWrapper<UserCart> queryWrapper = Wrappers.lambdaQuery();
        // 给查询对象加上ID限制和日期降序
        queryWrapper.eq(UserCart::getUserId,user.getId());
        Integer count = userCartMapper.selectCount(queryWrapper);
        return Result.success(count);
    }
}
